package com.itheima.aop;

import com.alibaba.fastjson.JSONObject;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Component
@Aspect
public class LogAop {
    @Pointcut("@annotation(com.itheima.aop.Log)")
    public void pt() {
    }

    @Autowired
    HttpServletRequest request;

    @Autowired
    OperateLogMapper operateLogMapper;

    @Around("pt()")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取操作人
        String jwt = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(jwt);
        Integer operateUser = (Integer) claims.get("id");

        //获取操作时间
        LocalDateTime operateTime = LocalDateTime.now();

        //获取操作类名
        String className = joinPoint.getTarget().getClass().getName();

        //获取操作的方法名
        String methodName = joinPoint.getSignature().getName();

        //获取操作方法的参数
        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.toString(args);

        //记录方法执行前的时间
        long begin = System.currentTimeMillis();

        //运行原始方法
        Object result = joinPoint.proceed();

        //获取方法的返回值
        String returnValue = JSONObject.toJSONString(result);

        //记录方法执行后的时间
        long end = System.currentTimeMillis();

        //记录方法运行的时长
        long costTime = end - begin;

        //组装日志对象
        OperateLog operateLog = new OperateLog(null, operateUser, operateTime, className, methodName, methodParams, returnValue, costTime);
        //调用记录日志的mapper通过sql语句插入操作日志
        operateLogMapper.insert(operateLog);
        log.info("AOP记录操作日志:{}", operateLog);
        return result;
    }
}
